package zmee.wfs.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: zyj
 * @Date: 2023/7/17 15:44
 * @Description: OA手动清除OA传阅: 点击清除OA传阅 清除OA系统的该条传阅消息
 */
public class OACleanSendmessageBillPlugin extends AbstractBillPlugIn {

    private static Log logger = LogFactory.getLog(OACleanSendmessageBillPlugin.class);

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate source = (FormOperate) args.getSource();
        String operateKey = source.getOperateKey();
        if ("oacleansendmessage".equals(operateKey)) {
            // OA传阅接口url
            String url = null;
            String returnResultStr = "";
            String returnMessage="";

            QFilter qFilter = new QFilter("number", QCP.equals, "OA");
            //获取消息渠道待办接口地址
            DynamicObject dynobj= BusinessDataServiceHelper.loadSingle("msg_channel","zmee_createtodo", new QFilter[]{qFilter});
            if(dynobj != null){
                url = dynobj.getString("zmee_createtodo");
            }
            if(StringUtils.isEmpty(url)){
                this.getView().showTipNotification("清除OA传阅消息失败！！，原因：OA消息渠道的待办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）");
                return;
            }
            // 这些信息从OA统一代办日志里面请求中拿 然后存在单据上
            // 异构系统标识
            String syscode = (String) this.getModel().getValue("zmee_syscode");
            // 流程实例id
            String flowid = (String) this.getModel().getValue("zmee_flowid");
            // 流程标题
            String requestname = (String) this.getModel().getValue("zmee_requestname");
            String workflowname = (String) this.getModel().getValue("zmee_workflowname");
            // PC地址
            String pcurl = (String) this.getModel().getValue("zmee_pcurl");
            // APP地址
            String appurl = (String) this.getModel().getValue("zmee_appurl");
            // 流程处理状态  4：办结
            String isremark = (String) this.getModel().getValue("zmee_isremark");
            // 流程查看状态  1：已读
            String viewtype = (String) this.getModel().getValue("zmee_viewtype");
            // 接收人账号
            String receiver = (String) this.getModel().getValue("zmee_receiver");
            // 时间戳字段
            String receivets = String.valueOf(System.currentTimeMillis());

            JSONObject requestJson = new JSONObject();
            requestJson.put("syscode", syscode);
            requestJson.put("flowid", flowid);
            requestJson.put("requestname", requestname);
            requestJson.put("workflowname", workflowname);
            requestJson.put("pcurl", pcurl);
            requestJson.put("appurl", appurl);
            requestJson.put("isremark", isremark);
            requestJson.put("viewtype", viewtype);
            requestJson.put("receiver", receiver);
            requestJson.put("receivets", receivets);
            logger.info("清除OA传阅：requestJson:"+requestJson.toString());

            logger.info("清除OA传阅调用接口的url：" + url + "\n清除OA传阅调用接口的参数：\n" + requestJson);
            //调用OA接口
            String returnResult = postData2ofs(url,requestJson.toString());
            if(returnResult==null||StringUtils.equals("",returnResult)){
                return;
            }
            JSONObject returnResultObj=JSONObject.fromObject(returnResult);
            returnResultStr=returnResult.toString();

            logger.info("sendMessage调用接口的返回值：" + returnResult);

            //操作结果
            returnMessage=returnResultObj.getString("message");

            this.getModel().setValue("zmee_cleanresult", returnMessage);
            this.getModel().setValue("zmee_response", returnResultStr);
        }
    }

    public String postData2ofs(String posturl, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(posturl);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }

            JSONObject object = JSONObject.fromObject(result);
            String returnResult = object.toString();
            String var11 = returnResult;
            return var11;
        } catch (Exception var21) {
            logger.error("zmee.wfs.formplugin.OACleanSendmessageBillPlugin,发送 POST请求出现异常！", var21.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }

        return null;
    }

}
